<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');
App::uses('CakeEmail', 'Network/Email');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

	var $components = array(
		'Session',
		'Auth'
	);
	var $uses = array(
		'Action',
		'ChangeLog',
		'Commission',
		'DeletedItem',
		'Market',
		'Name',
		'Person',
		'PersonType',
		'Transfer',
		'User',
	);

	protected $permissions = array();

	protected function requireClasses() {
		require_once(dirname(__FILE__) . '/../Lib/Errors.php');
		require_once(dirname(__FILE__) . '/../Lib/fpdf/tfpdf.php');
		require_once(dirname(__FILE__) . '/../Model/AppModel.php');
		require_once(dirname(__FILE__) . '/../Model/Action.php');
		require_once(dirname(__FILE__) . '/../Model/ChangeLog.php');
		require_once(dirname(__FILE__) . '/../Model/Commission.php');
		require_once(dirname(__FILE__) . '/../Model/DeletedItem.php');
		require_once(dirname(__FILE__) . '/../Model/Market.php');
		require_once(dirname(__FILE__) . '/../Model/Name.php');
		require_once(dirname(__FILE__) . '/../Model/Person.php');
		require_once(dirname(__FILE__) . '/../Model/PersonType.php');
		require_once(dirname(__FILE__) . '/../Model/Transfer.php');
		require_once(dirname(__FILE__) . '/../Model/User.php');
	}
	
	public function  beforeFilter() {
		$this->requireClasses();
		parent::beforeFilter();

		$this->Auth->allow('*');

		$session = $this->Session->read();
		$controller = $this->request->params['controller'];
		$action = $this->request->params['action'];

		$this->set('actualController', $controller);
		$this->set('actualAction', $action);
		
		if (isset($session['Auth']) && isset($session['Auth']['User']) && $session['Auth']['User']['id']) {
			$this->createMenuPermissions($session['Auth']['User'], $controller, $action);
			$this->set('actualUser', $session['Auth']['User']);
			if ($this->checkControllerActionAvailability($session['Auth']['User'], $controller, $action) === FALSE) {
				if ($controller != 'pages') {
					$this->setFlashError('Nemáte práva k tejto akcií ');// . $controller . ' ' . $action);
					$this->redirect(array('controller' => 'pages', 'action' => 'index'));
				}
			}
			if (in_array($session['Auth']['User']['Person']['fk_person_type_id'], PersonType::getEmployeeTypeList())) {
				$this->getSoonAnniversaries();
			}
		} else {
			$this->set('actualUser', NULL);
			if ($action !== 'login' && CRON_DISPATCHER !== TRUE) {
				// $this->setFlashError('Musíte sa prihlásiť');
				$this->redirect(array('controller' => 'user', 'action' => 'login'));
			}
		}
	}

	protected function checkControllerActionAvailability($user, $controller, $action) {
		if (isset($this->permissions[$controller][$action])) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	protected function createMenuPermissions($user, $actualController, $actualAction) {
		$personType = $this->PersonType->find('first', array('conditions' => array('PersonType.id' => $user['Person']['fk_person_type_id'])));
		$availableActions = array();
		$menuItems = array();
		// hack pre polozky person_type
		$additionalMenuItems = array();
		foreach ($personType['Actions'] as $action) {
			$availableActions[$action['controller']][$action['action']] = $action;
			if ($action['show_in_menu'] == 1) {
				// pridame do menu polozky z person type
				if ($action['controller'] == 'person_type') {
					if ($actualController == $action['controller'] && $actualAction == $action['action']) {
						$action['active'] = TRUE;
					}
					$additionalMenuItems[] = $action;
				} else {
					$action['active'] = FALSE;
					if ($actualController == $action['controller']) {
						$menuItems[$action['controller']]['active'] = TRUE;
						if ($actualAction == $action['action']) {
							$action['active'] = TRUE;
						}
					}
					$menuItems[$action['controller']]['title'] = $action['controller_title'];
					$menuItems[$action['controller']]['actions'][] = $action;
				}
			}
		}

		if (in_array($actualController, array('person', 'person_type'))) {
			$menuItems['person']['active'] = TRUE;
		}

		if (isset($menuItems['person']['actions']) && $additionalMenuItems) {
			$menuItems['person']['actions']['next_level'] = array();
			$menuItems['person']['actions']['next_level']['controller']['title'] = $additionalMenuItems[0]['controller_title'];
			if ($actualController == $additionalMenuItems[0]['controller']) {
				$menuItems['person']['actions']['next_level']['active'] = TRUE;
			}
			$menuItems['person']['actions']['next_level']['actions'] = $additionalMenuItems;
		}
		//print_r($menuItems);

		$this->set('menuItems', $menuItems);
		$this->permissions = $availableActions;
		$this->set('userPermissions', $availableActions);
	}

	protected function setFlashError($message) {
		$this->setFlashMessage($message, 'error');
	}

	protected function setFlashWarning($message) {
		$this->setFlashMessage($message, 'warning');
	}

	protected function setFlashSuccess($message) {
		$this->setFlashMessage($message, 'success');
	}

	private function setFlashMessage($message, $type) {
		$this->Session->setFlash(__($message), 'default', array('class' => 'flash ' . $type));
	}

	protected function sendMail($to, $subject, $message) {
		$mailer = new CakeEmail('smtp');
		$mailer->emailFormat('html');
		$mailer->to($to);
		$mailer->subject($subject);
		$mailer->send($message);
	}
	
	protected function getSoonAnniversaries() {
		// dnesne meniny
		$conditions = array(
			'day' => date('j'),
			'month' => date('n')
		);
		$nameList = $this->Name->find('all', array('fields' => 'name', 'conditions' => $conditions, 'limit' => 2));

		$names = array();
		foreach ($nameList as $name) {
			$names[] = $name['Name']['name'];
		}
		$this->set('todayNameList', implode(', ', $names));
		
		
		$thisMonth = date('n');
		$fiveDaysLater = strtotime('+5 days');
		$fiveDaysLaterMonth = date('n', $fiveDaysLater);

		if ($fiveDaysLaterMonth != $thisMonth) {
			$fiveDaysLaterDay = date('j', $fiveDaysLater);
			$conditions = array(
				'or' => array(
					array('Person.birth_day BETWEEN ' . (date('j')) . ' AND ' . (date('j') + 7), 'Person.birth_month' => $thisMonth),
					array('Person.birth_day BETWEEN 1 AND ' . $fiveDaysLaterDay, 'Person.birth_month' => $fiveDaysLaterMonth),
				)
			);

			$soonNamesConditions = array(
				'or' => array(
					array('day BETWEEN ' . (date('j')) . ' AND ' . (date('j') + 7), 'month' => $thisMonth),
					array('day BETWEEN 1 AND ' . $fiveDaysLaterDay, 'month' => $fiveDaysLaterMonth),
				)
			);
		} else {
			$conditions = array(
				'Person.birth_day BETWEEN ' . (date('j')) . ' AND ' . (date('j') + 7),
				'Person.birth_month' => $thisMonth,
			);

			$soonNamesConditions = array(
				'day BETWEEN ' . (date('j')) . ' AND ' . (date('j') + 7),
				'month' => $thisMonth,
			);
		}

		$soonBirthDayPersonList = $this->Person->find('all', array('conditions' => $conditions));
		$this->set('soonBirthDayPersonList', $soonBirthDayPersonList);
		
		$soonNameList = $this->Name->find('all', array('conditions' => $soonNamesConditions));
		$nameDates = array();
		$soonNameDayPersonList = array();
		foreach ($soonNameList as $name) {
			$conditions = array(
				'Person.name' => $name['Name']['name']
			);
			$soonNameDayPersonList = array_merge($soonNameDayPersonList, $this->Person->find('all', array('conditions' => $conditions)));
			
			$nameDates[Inflector::slug($name['Name']['name'])]['day'] = $name['Name']['day'];
			$nameDates[Inflector::slug($name['Name']['name'])]['month'] = $name['Name']['month'];
		}

		$this->set('nameDates', $nameDates);
		$this->set('soonNameDayPersonList', $soonNameDayPersonList);
		
		$calendarPopup = TRUE;
		$this->set('calendarPopup', $calendarPopup);
	}
}
